import 'dart:io';
import 'package:flutter/material.dart';
import 'dlna/dlna.dart';
import 'dlna/xmlParser.dart';
import 'package:flutter/services.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'toast.dart';
import 'dart:async';
import 'http_local.dart';

class DeviceControlPage extends StatefulWidget {
  final DLNADevice device;
  const DeviceControlPage({Key? key, required this.device}) : super(key: key);

  @override
  _DeviceControlPageState createState() => _DeviceControlPageState();
}

class _DeviceControlPageState extends State<DeviceControlPage> {
  double _volume = 0;
  PositionParser? position;
  VolumeParser? volume;
  HttpServer? _httpServer;
  Timer timer = Timer(const Duration(seconds: 1), () {});
  final TextEditingController _urlController = TextEditingController(
    text: "http://192.168.1.13:8080/yuanfenyidaoqiao.wav",
  );

  @override
  void initState() {
    super.initState();
    callback(_) async {
      try {
        final text = await widget.device.position();
        // print("update play progress: $text");
        final p = PositionParser(text);
        setState(() {
          position = p;
        });
      } catch (e) {
        print("update play progress failed: $e");
      }
    }

    _getVolume();
    timer = Timer.periodic(const Duration(seconds: 1), callback);
    callback(null);
  }

  @override
  void dispose() {
    _urlController.dispose();
    timer.cancel();
    super.dispose();
  }

  void _sendPlay() async {
    await widget.device.play();
  }

  void _sendPause() async {
    await widget.device.pause();
  }

  void _sendStop() async {
    await widget.device.stop();
  }

  void _setVolume(double value) async {
    await widget.device.volume(value.toInt());
  }

  void _getVolume() async {
    final text = await widget.device.getVolume();
    volume = VolumeParser(text);
    if (volume != null) {
      setState(() {
        _volume = volume!.current.toDouble();
      });
    }
  }

  void _setUrl() async {
    _sendStop();
    final url = _urlController.text.trim();
    if (url.isNotEmpty) {
      await widget.device.setUrl(url);
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('已设置媒体 URL')));
    }
  }

  void _sendSeek(String value) async {
    await widget.device.seek(value);
  }

  void _sendNext() async {
    await widget.device.next();
  }

  void _sendPrev() async {
    await widget.device.previous();
  }

  void _fastForwardTenSecond() async {
    final text = await widget.device.position();
    await widget.device.seekByCurrent(text, 10);
  }

  void _rewindTenSecond() async {
    final text = await widget.device.position();
    await widget.device.seekByCurrent(text, -10);
  }

  Future<void> _pickAudioFile() async {
    if (_httpServer != null) {
      await stopHttpServer(_httpServer!);
      _httpServer = null;
    }

    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null && result.files.single.path != null) {
      final filePath = result.files.single.path!;
      final file = File(filePath);

      if (await file.exists()) {
        _httpServer = await startHttpServer(filePath);
        final ip = await getLocalIpAddress();

        // 生成访问 URL
        final fileName = file.uri.pathSegments.last;
        final url = 'http://$ip:8088/$fileName';
        print(url);

        setState(() {
          _urlController.text = url;
        });
      } else {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('文件不存在')));
      }
    }
  }

  void _selectFile() async {
    try {
      if (_httpServer != null) {
        print("stopHttpServer");
        await stopHttpServer(_httpServer!);
        _httpServer = null;
      }

      // 选择文件
      final filePath = await FilePickerChannel.pickFile();
      if (filePath == null || filePath.isEmpty) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('未选择文件')));
        return;
      }
      print(filePath);
      final file = File(filePath);
      if (!await file.exists()) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('文件不存在')));
        return;
      }

      // 启动 HTTP 服务
      _httpServer = await startHttpServer(filePath);

      // 获取本地 IP 并生成访问 URL
      final ip = await getLocalIpAddress();
      final fileName = file.uri.pathSegments.last;
      final url = 'http://$ip:8088/$fileName';

      print('文件访问 URL: $url');

      // 更新 UI
      setState(() {
        _urlController.text = url;
      });
    } catch (e, stackTrace) {
      print('选择文件失败: $e');
      print(stackTrace);
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('发生错误，无法选择文件')));
    }
  }

  int parseTimeToSeconds(String time) {
    final parts = time.split(':').map(int.parse).toList();
    if (parts.length == 3) {
      return parts[0] * 3600 + parts[1] * 60 + parts[2];
    } else if (parts.length == 2) {
      return parts[0] * 60 + parts[1];
    } else if (parts.length == 1) {
      return parts[0];
    } else {
      return 0;
    }
  }

  String formatSecondsToTime(int seconds) {
    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;
    final secs = seconds % 60;
    return [
      hours,
      minutes,
      secs,
    ].map((v) => v.toString().padLeft(2, '0')).join(':');
  }

  Widget buildCurrUri() {
    if (position == null || position!.TrackURI.isEmpty) {
      return Container(
        alignment: Alignment.center,
        child: const Text("暂无视频信息"),
      );
    }

    var currUrl = position!.TrackURI;
    if (currUrl.length > 90) {
      currUrl = '${currUrl.substring(0, 90)}...';
    }

    return Container(
      alignment: Alignment.topLeft,
      padding: const EdgeInsets.all(10),
      child: Card(
        elevation: 1,
        color: Colors.white70,
        child: Container(
          padding: const EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 使用 Row 将 "当前播放:" 和 URL 放在同一行
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    "当前播放:",
                    style: TextStyle(fontSize: 12, color: Colors.blue),
                  ),
                  const SizedBox(width: 8), // 添加一点间距
                  Expanded(
                    child: InkWell(
                      child: Text(
                        currUrl,
                        style: const TextStyle(
                          fontSize: 14,
                          color: Colors.orange,
                        ),
                        softWrap: true,
                      ),
                      onTap: () {
                        ClipboardData data = ClipboardData(
                          text: position!.TrackURI,
                        );
                        Clipboard.setData(data);
                        toast("已复制");
                      },
                    ),
                  ),
                ],
              ),
              if (position!.AbsTime.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 8.0),
                  child: Text(
                    "${position!.RelTime} / ${position!.TrackDuration}",
                    style: const TextStyle(fontSize: 14),
                  ),
                ),
              if (position!.RelTime.isNotEmpty &&
                  position!.TrackDuration.isNotEmpty)
                Padding(
                  padding: const EdgeInsets.only(top: 2.0),
                  child: Column(
                    children: [
                      Slider(
                        value: parseTimeToSeconds(position!.RelTime).toDouble(),
                        max: parseTimeToSeconds(
                          position!.TrackDuration,
                        ).toDouble(),
                        min: 0,
                        onChanged: (v) {},
                        onChangeEnd: (v) {
                          final seekTime = formatSecondsToTime(v.toInt());
                          _sendSeek(seekTime);
                          toast("跳转至 $seekTime");
                        },
                      ),
                    ],
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('${widget.device.info.friendlyName} 控制')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '设备名称: ${widget.device.info.friendlyName}',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 8),
            Text('设备地址: ${widget.device.info.URLBase}'),
            SizedBox(height: 8),
            SizedBox(
              height: 60,
              child: TextField(
                controller: _urlController,
                decoration: const InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: '媒体 URL',
                  contentPadding: EdgeInsets.symmetric(
                    horizontal: 12,
                    vertical: 10,
                  ),
                ),
              ),
            ),
            SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () {
                    if (Platform.isAndroid) {
                      _selectFile();
                    } else {
                      _pickAudioFile();
                    }
                  },
                  child: const Text('选择音频文件'),
                ),
                ElevatedButton(onPressed: _setUrl, child: Text('投屏设置URL')),
              ],
            ),
            SizedBox(height: 2),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(onPressed: _sendPlay, child: Text('播放')),
                ElevatedButton(onPressed: _sendPause, child: Text('暂停')),
                ElevatedButton(onPressed: _sendStop, child: Text('停止')),
              ],
            ),
            SizedBox(height: 2),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: _rewindTenSecond,
                  child: Text('快退10秒'),
                ),
                ElevatedButton(
                  onPressed: _fastForwardTenSecond,
                  child: Text('快进10秒'),
                ),
              ],
            ),
            // SizedBox(height: 2),
            // Row(
            //   mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            //   children: [
            //     ElevatedButton(
            //       onPressed: _sendPrev,
            //       child: Text('上一首'),
            //     ),
            //     ElevatedButton(
            //       onPressed: _sendNext,
            //       child: Text('下一首'),
            //     ),
            //   ],
            // ),
            SizedBox(height: 8),
            Text('音量: ${_volume.toInt()}'),
            Slider(
              value: _volume,
              min: 0,
              max: 100,
              divisions: 20,
              label: _volume.toInt().toString(),
              onChanged: (value) {
                setState(() => _volume = value);
                _setVolume(value);
              },
            ),
            SizedBox(height: 180, child: buildCurrUri()),
          ],
        ),
      ),
    );
  }
}

class FilePickerChannel {
  static const MethodChannel _channel = MethodChannel('custom_file_picker');

  static Future<String?> pickFile() async {
    try {
      final String? path = await _channel.invokeMethod('pickFile');
      return path;
    } on PlatformException catch (e) {
      print('Failed to pick file: $e');
      return null;
    }
  }
}
